package it.win4buy.datamodel;

import it.win4buy.connectionpool.ConnectionPool;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;

import org.w3c.dom.Document;

public class TablesBean {

	private static final long serialVersionUID = 1L;
	private ConnectionPool connectionPool = null;
	private static Connection connection = null;

	Document doc = null;
	String tipiTavoloQY = "SELECT * FROM tipi_tavolo";
	String tavoliGiocoQY = "SELECT * FROM tavoli_gioco where tipo_tavolo=? AND stato_tavolo=1";
	Vector tipiTavolo = new Vector();
	private boolean debugMode = false;

	private ArrayList tables = new ArrayList();

	public void addTable(TableBean table) {
		tables.add(table);
	}

	public ArrayList getTables() {
		return tables;
	}

	private void loadTables() {
		PreparedStatement preparedStatement = null;
		ResultSet rs;
		try {
			connection = connectionPool.getConnection();

			preparedStatement = connection.prepareStatement(tipiTavoloQY);
			rs = preparedStatement.executeQuery();
			while (rs.next()) {
				tipiTavolo.add(new Integer(rs.getInt("id")));
			}
			rs.close();
			preparedStatement.close();

			for (int i = 0; i < tipiTavolo.size(); i++) {
				try {
					preparedStatement = connection
							.prepareStatement(tavoliGiocoQY);

					preparedStatement.setInt(1, new Integer(tipiTavolo
							.elementAt(i).toString()).intValue());
					rs = preparedStatement.executeQuery();
					if (!rs.next()) {
						preparedStatement.close();
						rs.close();
						preparedStatement = connection
								.prepareStatement("INSERT INTO tavoli_gioco (tipo_tavolo,data_ora_creazione) VALUES("
										+ tipiTavolo.elementAt(i) + ",NOW())");
						preparedStatement.executeUpdate();

					}

				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			connectionPool.releaseConnection(connection);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
